package com.xk._02算法篇._01sort.sort;

import com.xk.tools.Integers;

/**
 * @description: 计数排序
 * @author: xu
 * @date: 2022/10/2 10:43
 */
public class CountingSort1 extends Sort<Integer> {

    /**
     * 计数排序
     */
    private void countingSort(){
        // 找出最大值
        int max = array[0];
        for (int i = 1; i < array.length; i++) {
            if (array[i] > max) max = array[i];
        }
        //开辟内存空间，存储每个整数出现的次数
        int[] counts = new int[max + 1];
        // 统计每个整数出现的次数
        for (int i = 0; i < array.length; i++) {
            counts[array[i]]++;
        }
        // 根据整数的出现次数，对整数进行排序
        int index = 0;
        for (int i = 0; i < counts.length; i++) {
            while (counts[i]-- > 0){
                array[index++] = i;
            }
        }
    }

    @Override
    protected void sort() {
        countingSort();
    }

    public static void main(String[] args) {
        Integer[] array = Integers.random(32, 1, 100);
        Integers.println(array);

        Sort<Integer> mergeSort = new CountingSort1();
        mergeSort.sort(array);
        Integers.println(array);
        System.out.println(mergeSort);
    }
}
